package com.enjoy.concurrent.ch2;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

@Slf4j(topic = "enjoy")
public class CyclicBarrierTest {

    private final CyclicBarrier cyclicBarrier = new CyclicBarrier(2, new Thread(() -> log.info("任务完成")));

    @Test
    public void test1() throws InterruptedException {
        for (int i = 0; i < 8; i++) {
            new Thread(() -> {
                try {
                    log.info("开始执行任务");
                    Thread.sleep(3000);
                    log.info("到达屏障A");
                    cyclicBarrier.await();

                } catch (InterruptedException | BrokenBarrierException e) {
                    log.error(e.getMessage());
                }

            }, "t" + i).start();
        }
        TimeUnit.MINUTES.sleep(1);
    }

    public static class Task implements Runnable {

        CyclicBarrier cyclicBarrier;



        public Task(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(1000);

                log.info("到达栅栏A");
                cyclicBarrier.await();
                log.info("冲出栅栏A");


            } catch (InterruptedException | BrokenBarrierException e) {
                log.error(e.getMessage());
            }
        }
    }

    @Test
    public void test2() throws InterruptedException {

        for (int i = 0; i < 5; i++) {
            new Thread(new Task(cyclicBarrier), "t" + i).start();
        }

        Thread.sleep(1000000000);
    }


}
